<template>
  <div class="container">
    <mt-field label="楼盘名称："
              v-model="cp.premisesName"
              readonly></mt-field>
    <div v-if="agentReportFlag">
      <mt-field label="代报备人："
                v-model="cp.partnerName"
                readonly></mt-field>
      <mt-field label="联系电话："
                v-model="cp.partnerPhone"
                readonly></mt-field>
    </div>
    <mt-field v-if="agentReportFlag"
              label="经纪人："
              v-model="cp.staffName"
              readonly></mt-field>
    <mt-field v-else
              label="报备人："
              v-model="cp.staffName"
              readonly></mt-field>
    <mt-field label="联系电话："
              v-model="cp.staffPhone"
              readonly></mt-field>
    <mt-field label="当前状态："
              v-model="customerStatusText"
              readonly></mt-field>
    <mt-field :label="statusTitle"
              v-model="newStatusText"
              readonly></mt-field>
    <div class="mint-cell mint-field"
         v-if="visitedFlag"
         v-res="menu_0008_0001_0002_0001">
      <div class="mint-cell-wrapper">
        <div class="mint-cell-title">
          <span class="mint-cell-text">实际到访时间</span>
        </div>
        <div class="mint-cell-value">
          <input type="text"
                 name="date"
                 @click="openDatePicker"
                 placeholder="实际到访时间"
                 v-model="createTimeText"
                 readonly
                 :disabled="editVisitTimeFlag">
          <a class="edit-visited-time"
             @click="editVisitTime">修改实际到访时间</a>
          <!-- <mt-datetime-picker ref="datePicker"
                              type="datetime"
                              v-model="createTime"
                              @confirm="handleConfirm"></mt-datetime-picker> -->
        </div>
      </div>
    </div>
    <div class="mint-cell mint-field"
         v-if="adviserList.length > 0 && newStatus == 6">
      <div class="mint-cell-wrapper">
        <div class="mint-cell-title">
          <span class="mint-cell-text">置业顾问：</span>
        </div>
        <div class="mint-cell-value">
          <input style="width: 80%;"
                 type="text"
                 name="jjr"
                 placeholder="请选择"
                 v-model="adviserName"
                 @click="showAdviser"
                 readonly>
        </div>
      </div>
    </div>
    <div class="mint-cell mint-field"
         v-if="enabled">
      <div class="mint-cell-wrapper">
        <div class="mint-cell-title">
          <span class="mint-cell-text">无效原因：</span>
        </div>
        <div class="mint-cell-value">
          <input style="width: 80%;"
                 type="text"
                 name="jjr"
                 placeholder="请选择"
                 v-model="reasonText"
                 @click="openReasonPicker"
                 readonly>
        </div>
      </div>
    </div>
    <mt-field label="备注信息："
              v-model="remark"
              v-if="enabledReason"></mt-field>

    <div class="unified-template"
         style="margin-top: 10px;padding: 10px;">
      <div class="titlePhoto">
        <div style="font-weight: 400;font-size:16px;">上传图片</div>
        <div style="font-size:12px;color:#ccc;">最多上传5张</div>
      </div>
      <ul class="photo-list">
        <li v-for="(row, index) in fileList">
          <img v-bind:src="row.file"
               @click="previewImage(index)">
          <i class="fa fa-times-circle"
             @click="deletefile(index)"></i>
        </li>
        <li class="departureBtn">
          <a href="javascript:;">
            <i class="fa fa-plus"></i>
          </a>
          <input type="file"
                 class="fileBtn"
                 @change="upload"
                 name="files"
                 id="files">
        </li>
      </ul>
      <div class="clearfix"></div>
    </div>
    <div class="operationBtn">
      <button class="btn btn-line btn-primary"
              @click="btnSubmit">提交</button>
      <button class="btn btn-line btn-cancel"
              @click="btnCancel">取消</button>
    </div>

    <mt-popup v-model="reasonVisible"
              position="bottom"
              style="width: 100%;">
      <mt-picker ref="reasonPicker"
                 :slots="slots"
                 @change="onValuesChange"
                 valueKey="text"></mt-picker>
    </mt-popup>
    <mt-popup v-model="popupAdviser"
              position="bottom"
              class="mint-popup mint-datetime mint-popup-bottom">
      <div class="">
        <div class="picker-toolbar">
          <div class="mint-datetime-action left"
               style="width: 49%;"
               @click="popupAdviser=false">取消</div>
          <div class="mint-datetime-action left"
               style="width: 49%;"
               @click="confirmAdviser">确定</div>
        </div>
        <mt-picker :slots="adviserDDL"
                   value-key='label'
                   :item-height="48"
                   @change="selectAdviser"></mt-picker>
      </div>
    </mt-popup>
    <popup v-model="popShow"
           position="bottom">
      <datetime-picker v-model="createTime"
                       @confirm="handleConfirm"
                       @cancel="handleCancel"
                       ref="datePicker"
                       type="datetime" />
    </popup>
  </div>
</template>

<script>
import { Toast } from "mint-ui";
import Exif from "exif-js";
import wx from "weixin-js-sdk";
import Popup from "vant/lib/popup";
import DatetimePicker from "vant/lib/datetime-picker";
import "vant/lib/popup/style";
import "vant/lib/datetime-picker/style";
export default {
  name: "audit-report",
  components: { Toast, Popup, DatetimePicker },
  data() {
    return {
      slots: [
        {
          defaultIndex: 0,
          values: [
            { id: 1, text: "无效电话号码" },
            { id: 2, text: "无购房意向" },
            { id: 3, text: "其他" }
          ]
        }
      ],
      imageList: [],
      fileList: [],
      cp: {},
      newStatus: "",
      remark: "",
      customerStatusText: "",
      newStatusText: "",
      createTimeText: "",
      createTime: "",
      editVisitTimeFlag: true,
      visitedFlag: false,
      reasonVisible: false,
      enabled: false,
      enabledReason: true,
      reasonText: "无效电话号码",
      agentReportFlag: false,
      statusTitle: "报备状态",
      adviserUuid: "",
      adviserName: "",
      adviserPhone: "",
      popupAdviser: false,
      tempAdviser: { value: "", label: "请选择置业顾问" },
      adviserList: [],
      adviserDDL: [],
      popShow: false
    };
  },
  mounted() {
    this.cp = this.$route.params.cp;
    this.newStatus = this.$route.params.newStatus;
    // 报备列表的数据和详情页的数据不一致，这里做处理
    if (!this.cp.partnerName && this.cp.assistantName) {
      this.cp.partnerName = this.cp.assistantName;
      this.cp.partnerPhone = this.cp.assistantPhone;
    }

    if (this.cp.customerStatus == 0) {
      this.statusTitle = "报备状态";
    } else if (this.cp.customerStatus == 10) {
      this.statusTitle = "到访状态";
    }
    if (this.newStatus == 10) {
      this.newStatusText = "报备有效";
    } else if (this.newStatus == 6) {
      this.visitedFlag = true;
      this.handleConfirm(new Date());
      this.newStatusText = "到访有效";
    } else if (this.newStatus == -1) {
      this.enabled = true;
      this.enabledReason = false;
      this.newStatusText = "报备无效";
    }
    //如果为代报备
    if (!this.cp.partnerName) {
      this.agentReportFlag = false;
    } else {
      this.agentReportFlag = true;
    }
    this.customerStatusText =
      this.cp.currentStatus || this.cp.customerStatusName;
    this.initAdviserList();
  },
  methods: {
    btnSubmit() {
      //提交审核
      //报备有效
      var _self = this;
      var body = {};
      body.params = {
        id: _self.cp.id,
        customerStatus: _self.newStatus,
        affixList: _self.imageList,
        adviserUuid: _self.adviserUuid
      };
      if (_self.newStatus == 6) {
        body.params.createTime = this.createTime;
        if (_self.editVisitTimeFlag) {
          body.params.createTime = new Date();
        }
      }
      if (_self.enabledReason) {
        body.params.remark = _self.remark;
      } else {
        body.params.remark = _self.reasonText;
      }
      var url = _self.utilHelper.apiUrl + "/api/auditCP";
      _self.$http.post(url, body).then((response) => {
        var data = response.body.resData;
        var result = data.result;
        var errorMsg = data.resultMsg;
        if ("1" == result) {
          var instance = Toast("操作成功!");
          setTimeout(() => {
            instance.close();
          }, 2000);
          //报备有效,显示到访有效按钮
          // row.visitedValidShow = true;
          // row.customerStatusName = "报备有效";
          // _self.$router.push({ path: "/confirmList" });
          this.$router.push({
            path: "/confirmList",
            query: { customerStatus: this.cp.customerStatus }
          });
        } else {
          var instance = Toast(errorMsg);
          // row.reportValidShow = true;
          setTimeout(() => {
            instance.close();
          }, 2000);
        }
      });
    },
    btnCancel() {
      var _self = this;
      // _self.$router.push({ path: "/confirmList" });
      this.$router.push({
        path: "/confirmList",
        query: { customerStatus: this.cp.customerStatus }
      });
    },
    handleConfirm(e) {
      var date = new Date(e);
      var visitProtectDate =
        date.getFullYear() +
        "-" +
        this.fomrtDate(date.getMonth() + 1) +
        "-" +
        this.fomrtDate(date.getDate()) +
        " " +
        this.fomrtDate(date.getHours()) +
        ":" +
        this.fomrtDate(date.getMinutes());
      ":" + this.fomrtDate(date.getSeconds());
      this.createTimeText = visitProtectDate;
      this.createTime = date;
      this.popShow = false;
    },
    handleCancel() {
      this.popShow = false;
    },
    fomrtDate(n) {
      return n >= 10 ? n : "0" + n;
    },
    openDatePicker() {
      this.popShow = true;
      // this.$refs.datePicker.open();
    },
    openReasonPicker() {
      this.reasonVisible = true;
    },
    onValuesChange(picker) {
      var type = picker.getSlotValue(0);
      console.log(type);
      if (!type || !type.id) {
        return;
      }
      this.reasonText = type.text;
      if (type.id == 1 || type.id == 2) {
        this.enabledReason = false;
        this.remark = type.text;
      } else {
        this.remark = "";
        this.enabledReason = true;
      }
    },
    //////////////////////////图片上传//////////////////////////
    upload(e) {
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      this.picValue = files[0];
      this.imgPreview(this.picValue);
    },
    imgPreview(file) {
      let self = this;
      let Orientation;
      //去获取拍照时的信息，解决拍出来的照片旋转问题
      Exif.getData(file, function () {
        Orientation = Exif.getTag(this, "Orientation");
      });
      // 看支持不支持FileReader
      if (!file || !window.FileReader) return;

      if (/^image/.test(file.type)) {
        // 创建一个reader
        let reader = new FileReader();
        // 将图片2将转成 base64 格式
        reader.readAsDataURL(file);
        // 读取成功后的回调
        reader.onloadend = function () {
          let result = this.result;
          let img = new Image();
          img.src = result;
          //判断图片是否大于1m,是就直接上传，反之压缩图片
          if (this.result.length <= 500 * 1024) {
            self.ajaxfile(this.result);
          } else {
            img.onload = function () {
              let data = self.compress(img, Orientation);
              self.ajaxfile(data);
            };
          }
        };
      }
    },
    rotateImg(img, direction, canvas) {
      //最小与最大旋转方向，图片旋转4次后回到原方向
      const min_step = 0;
      const max_step = 3;
      if (img == null) return;
      //img的高度和宽度不能在img元素隐藏后获取，否则会出错
      let height = img.height;
      let width = img.width;
      let step = 2;
      if (step == null) {
        step = min_step;
      }
      if (direction == "right") {
        step++;
        //旋转到原位置，即超过最大值
        step > max_step && (step = min_step);
      } else {
        step--;
        step < min_step && (step = max_step);
      }
      //旋转角度以弧度值为参数
      let degree = (step * 90 * Math.PI) / 180;
      let ctx = canvas.getContext("2d");
      switch (step) {
        case 0:
          canvas.width = width;
          canvas.height = height;
          ctx.drawImage(img, 0, 0);
          break;
        case 1:
          canvas.width = height;
          canvas.height = width;
          ctx.rotate(degree);
          ctx.drawImage(img, 0, -height);
          break;
        case 2:
          canvas.width = width;
          canvas.height = height;
          ctx.rotate(degree);
          ctx.drawImage(img, -width, -height);
          break;
        case 3:
          canvas.width = height;
          canvas.height = width;
          ctx.rotate(degree);
          ctx.drawImage(img, -width, 0);
          break;
      }
    },
    compress(img, Orientation) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      //瓦片canvas
      let tCanvas = document.createElement("canvas");
      let tctx = tCanvas.getContext("2d");
      let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      let ratio;
      if ((ratio = (width * height) / 4000000) > 1) {
        console.log("大于400万像素");
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }
      canvas.width = width;
      canvas.height = height;
      //        铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      //如果图片像素大于100万则使用瓦片绘制
      let count;
      if ((count = (width * height) / 1000000) > 1) {
        console.log("超过100W像素");
        count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
        //            计算每块瓦片的宽和高
        let nw = ~~(width / count);
        let nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(
              img,
              i * nw * ratio,
              j * nh * ratio,
              nw * ratio,
              nh * ratio,
              0,
              0,
              nw,
              nh
            );
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }
      //修复ios上传图片的时候 被旋转的问题
      if (Orientation != "" && Orientation != 1) {
        switch (Orientation) {
          case 6: //需要顺时针（向左）90度旋转
            this.rotateImg(img, "left", canvas);
            break;
          case 8: //需要逆时针（向右）90度旋转
            this.rotateImg(img, "right", canvas);
            break;
          case 3: //需要180度旋转
            this.rotateImg(img, "right", canvas); //转两次
            this.rotateImg(img, "right", canvas);
            break;
        }
      }
      //进行最小压缩
      let ndata = canvas.toDataURL("image/jpeg", 0.1);
      console.log("压缩前：" + initSize);
      console.log("压缩后：" + ndata.length);
      console.log(
        "压缩率：" + ~~((100 * (initSize - ndata.length)) / initSize) + "%"
      );
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    },
    //////////////////////////图片上传//////////////////////////
    /////////////////////////////////////图片上传方法//////////////////////////////////////////
    createImage(file) {
      var _self = this;
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (e) {
        _self.ajaxfile(e.target.result);
      };
    },
    //将base64转换blob
    dataURLtoBlob(dataUrl) {
      var arr = dataUrl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    //上传图片
    ajaxfile(file) {
      var _self = this;
      if (_self.imageList.length == 5) {
        layer.msg("最多上传5张图片");
        return;
      }
      var myForm = new FormData(); //创建formdata
      var blobBin = _self.dataURLtoBlob(file); //base64转换blob
      myForm.append("blobObject", blobBin); //想formData添加blob数据
      var url = _self.utilHelper.apiUrl + "/api/uploadBase64";
      _self.$http.post(url, myForm).then((response) => {
        layer.closeAll("loading"); //关闭加载层
        var data = response.body;
        if (data.result == "1") {
          var filesUrl = {
            url: data.resData.imgName,
            isQiNiu: false
          };
          _self.imageList.push(filesUrl);
          var fileName = {
            file: file
          };
          _self.fileList.push(fileName);
        } else {
          layer.msg("图片上传失败，请重试");
        }
      });
    },
    //图片预览
    previewImage(index) {
      var _self = this;
      var imgList = new Array();
      for (var i = 0; i < _self.imageList.length; i++) {
        imgList.push(_self.imageList[i].url);
      }
      wx.previewImage({
        current: imgList[index],
        urls: imgList
      });
    },
    //删除图片
    deletefile(id) {
      this.imageList.splice(id, 1);
      this.fileList.splice(id, 1);
    },
    /////////////////////////////////////图片上传方法//////////////////////////////////////////
    editVisitTime() {
      this.editVisitTimeFlag = false;
      this.openDatePicker();
    },
    initAdviserList() {
      let premisesId = this.cp.premisesId;
      console.log("premisesId = " + premisesId);
      var url = this.utilHelper.apiUrl + "/api/premises/adviser/list";
      var body = {};
      body.params = {
        id: premisesId
      };
      this.$http.post(url, body).then((response) => {
        var body = response.body;
        if (1 == body.result) {
          var newAdviserArr = [];
          var emptyAdviser = { value: "", label: "请选择置业顾问", phone: "" };
          newAdviserArr.push(emptyAdviser);
          var adviserList = body.resData.list;
          this.adviserList = adviserList;
          adviserList.forEach((element) => {
            var obj = {};
            obj.value = element.adviserUuid;
            obj.label = element.name;
            obj.phone = element.phone;
            newAdviserArr.push(obj);
          });
          var adviserObj = {};
          adviserObj.values = newAdviserArr;
          this.adviserDDL.push(adviserObj);
        } else {
          Toast({
            message: "数据获取失败",
            position: "middle",
            duration: 2000
          });
        }
      });
    },
    showAdviser() {
      this.popupAdviser = true;
    },
    confirmAdviser() {
      this.adviserUuid = this.tempAdviser.value;
      this.adviserName = this.tempAdviser.label;
      this.adviserPhone = this.tempAdviser.phone;
      this.popupAdviser = false;
    },
    selectAdviser(picker, values) {
      if (values && values.length > 0) {
        this.tempAdviser = values[0];
        // this.customerInfo.adviserUuid = values[0].value;
        // this.customerInfo.adviserName = values[0].label;
        // this.customerInfo.adviserPhone = values[0].phone;
      }
    }
  }
};
</script>

<style scoped>
.unified-template {
  padding: 0 10px;
  background-color: #fff;
}
.titlePhoto {
  font-weight: normal;
  padding: 10px;
  float: left;
}
.photo-list {
  float: left;
}
.photo-list li {
  float: left;
  width: 64px;
  height: 64px;
  position: relative;
  border: 1px solid #cdcdcd;
  margin: 0 5px 10px;
}
.photo-list li > img {
  width: 100%;
  height: 100%;
}
.photo-list > li .fa-times-circle {
  position: absolute;
  right: -8px;
  top: -8px;
  color: #ff6666;
  font-size: 18px;
}
.photo-list .departureBtn {
  border: none;
}
.departureBtn > a {
  border: 1px dashed #7f7f7f;
  height: 100%;
  display: block;
  text-align: center;
}
.departureBtn > a .fa-plus {
  font-size: 30px;
  color: #7f7f7f;
  margin-top: 16px;
}
.departureBtn .fileBtn {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
  opacity: 0;
}

.clearfix:after,
.container:after {
  content: "";
  display: block;
  clear: both;
  visibility: hidden;
  overflow: hidden;
  font-size: 0;
  height: 0;
}

.operationBtn {
  margin-top: 56px;
  padding: 0 12px;
}
.btn {
  font-size: 14px;
  font-weight: 400;
  line-height: 1.42;
  position: relative;
  color: #fff;
  display: inline-block;
  margin-bottom: 0;
  padding: 6px 21px;
  cursor: pointer;
  -webkit-transition: all;
  transition: all;
  -webkit-transition-timing-function: linear;
  transition-timing-function: linear;
  -webkit-transition-duration: 0.2s;
  transition-duration: 0.2s;
  text-align: center;
  vertical-align: top;
  white-space: nowrap;
  color: #333;
  border-radius: 3px;
  background-color: #fff;
}
.btn-primary {
  background-color: #ff7900;
  color: #fff;
}
.btn-line {
  display: block;
  width: 100%;
  padding-top: 10px;
  padding-bottom: 10px;
  margin-bottom: 14px;
}
.btn-cancel {
  background-color: #999;
  color: #fff;
}
.edit-visited-time {
  color: #f90;
  font-size: 12px;
  width: 50px;
}
</style>
